package com.iteaj.iot.test.mqtt;

import com.iteaj.iot.AbstractProtocol;
import com.iteaj.iot.client.mqtt.MqttClientComponent;
import com.iteaj.iot.client.mqtt.MqttConnectProperties;
import com.iteaj.iot.client.mqtt.message.MqttMessageHead;
import com.iteaj.iot.test.TestMultiClientManager;
import com.iteaj.iot.test.TestProtocolType;
import io.netty.handler.codec.mqtt.MqttMessageBuilders;
import io.netty.handler.codec.mqtt.MqttQoS;

public class MqttClientTestComponent extends MqttClientComponent<MqttClientTestMessage> {

    public static final String WillTopic = "/willTopic/#";

    public MqttClientTestComponent(MqttConnectProperties config) {
        super(config, new TestMultiClientManager());
    }

    @Override
    protected void doSubscribe(MqttMessageBuilders.SubscribeBuilder subscribe, MqttConnectProperties client) {
        // 订阅客户端下线的遗嘱
        if(client.getWillTopic() == null) {
            subscribe.addSubscription(MqttQoS.AT_MOST_ONCE, WillTopic);

            // 订阅对应的Qos等级
            subscribe.addSubscription(MqttQoS.AT_MOST_ONCE, MqttClientTestHandle.AT_MOST_ONCE_TOPIC);
            subscribe.addSubscription(MqttQoS.EXACTLY_ONCE, MqttClientTestHandle.EXACTLY_ONCE_TOPIC);
            subscribe.addSubscription(MqttQoS.AT_LEAST_ONCE, MqttClientTestHandle.AT_LEAST_ONCE_TOPIC);
        } else {
            subscribe.addSubscription(MqttQoS.FAILURE, "");
        }
    }

    @Override
    public String getName() {
        return "mqtt协议";
    }

    @Override
    public String getDesc() {
        return "用于测试mqtt协议";
    }

    @Override
    public AbstractProtocol getProtocol(MqttClientTestMessage message) {
        MqttMessageHead head = message.getHead();
        if(head.getType() == TestProtocolType.CIReq) {
            return remove(head.getMessageId());
        } else if(head.getType() == TestProtocolType.PIReq){
            return new MqttSubscribeTestProtocol(message);
        } else if(head.getType() == TestProtocolType.WillTop) {
            return new MqttSubscribeTestProtocol(message);
        } else {
            return null;
        }
    }
}
